#include "cedit.h"

/**
 * CEdit - constructor, creates edit
 * @param text
 */
CEdit::CEdit(string text) {
  this->init();
  this->text = text;
}
//---------------------------------------------------------------------------

/**
 * getText - returns text
 * @return text
 */
string CEdit::getText() const {
  return text;
}
//---------------------------------------------------------------------------

/**
 * setText - sets text
 * @param text
 */
void CEdit::setText(string text) {
  this->text = text;
}
//---------------------------------------------------------------------------

/**
 * keyDown - key press on edit box
 * @param keyId
 * @param unicode
 */
void CEdit::keyDown(unsigned short keyId, unsigned short unicode) {
  
  // If backspace was pressed, text is truncated by one character
  // Otherwise if another key was pressed, its character is added to string

  switch (keyId) {
    case CKeyIdentifications::KEY_BACKSPACE :
      if (text.length()) {
        text = text.substr(0, text.length() - 1);
      }
      break;
    case CKeyIdentifications::KEY_SPACE :
      text += " ";
      break;
    default :
      if ((unicode & 0xFF80) == 0) {
        text += (unicode & 0x7F);
      }
      break;
  }
}
//---------------------------------------------------------------------------

/**
 * drawSelf - draw edit box
 * @param rendererPtr
 */
void CEdit::drawSelf(CGuiRenderer* rendererPtr) {

  // Edit dimensions without border
  unsigned short w(width - (style.getBorder().getSize() << 1));
  unsigned short h(height - (style.getBorder().getSize() << 1));

  // Edit text dimensions
  unsigned short textW(rendererPtr->calculateTTFWidth(fontId, text));
  unsigned short textH(rendererPtr->calculateTTFHeight(fontId));

  // If text height is greater that height of edit, return
  if (textH > h) {
    return;
  }

  // Truncate text until it fits edit width
  string tmp(text + "_ ");
  while (tmp.length() && rendererPtr->calculateTTFWidth(fontId, tmp) > w) {
    tmp = tmp.substr(1);
  }
  textW = rendererPtr->calculateTTFWidth(fontId, tmp);

  // If text still does not fit, return
  if (textW > w) {
    return;
  }

  // Draw text
  int l(x + ((width - textW) >> 1)), t(y + ((height - textH) >> 1));
  rendererPtr->drawTextRect(l, t, l + textW, t + textH, fontId, tmp);
}
//---------------------------------------------------------------------------
